<!-- 优惠券管理 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-input class="fix_input" v-model.trim="seacherData.title" type="text" autocomplete="off"
                        placeholder="请输入优惠券名称" clearable @clear="init()" />
                    <el-select class="frame" placeholder="请选择优惠券类型" v-model="seacherData.type">
                        <el-option v-for="item in couponType" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <el-select class="frame" placeholder="请选择优惠券状态" v-model="seacherData.status">
                        <el-option v-for="item in couponStatus" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <el-button :icon="Search" type="primary" @click="search()">查找</el-button>
                    <el-button :icon="Plus" type="primary" @click="addRole();">添加</el-button>
                    <el-button :icon="Download" type="primary" @click="handleDownload();">当前页导出</el-button>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item"
                        v-loading="listLoading" element-londing-text="正在加载中...">
                        <el-table-column prop="id" label="优惠券ID" align="center" width="100" />
                        <el-table-column prop="title" label="优惠券名称" align="center" width="180" />
                        <el-table-column prop="type" label="优惠券类型" align="center" width="180">
                            <template #default="scope">
                                {{ scope.row.type == 1 ? '满减券' : '立减券' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="description" label="介绍" align="center" width="180" />
                        <el-table-column prop="total" label="优惠券数量" align="center" width="100" />
                        <el-table-column prop="surplus" label="剩余数量" align="center" width="100" />
                        <el-table-column prop="limit" label="每人限领" align="center" width="100" />
                        <el-table-column prop="title" label="满减金额" align="center" width="100">
                            <template #default="scope">
                                减免{{ scope.row.discount / 100 }}元
                            </template>
                        </el-table-column>
                        <el-table-column prop="min" label="最低消费" align="center" width="180">
                            <template #default="scope">
                                满{{ scope.row.min / 100 }}元可用
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" align="center" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 0 ? 'danger' : scope.row.status == 1 ? '' : 'danger'">
                                    {{ scope.row.status == 0 ? '下架' : scope.row.status == 1 ? '正常' : '已过期' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryTitle" label="使用类目名称" align="center" width="100">
                            <template #default="scope">
                                <el-tag>
                                    {{ scope.row.categoryTitle ? scope.row.categoryTitle : '全部类目' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryId" label="使用类目ID" align="center" width="100" />
                        <el-table-column prop="days" label="领劵相对天数" align="center">
                            <template #default="scope">
                                {{ scope.row.days ? scope.row.days : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtStart" label="领劵开始时间" align="center" width="180">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ scope.row.gmtStart ? handleTime(scope.row.gmtStart, '-ymdhmm') : "无" }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtEnd" label="领劵结束时间" align="center" width="180">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ scope.row.gmtEnd ? handleTime(scope.row.gmtEnd, '-ymdhmm') : "无" }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="180">
                            <template #default="scope">
                                <el-button
                                    :type="scope.row.status == 0 ? 'primary' : scope.row.status == 1 ? 'danger' : 'primary'"
                                    @click="handleFreeze(scope.$index, scope.row)">
                                    {{ scope.row.status == 0 ? '激活' : scope.row.status == 1 ? '冻结' : '已过期' }}
                                </el-button>
                                <el-button type="info" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" destroy-on-close>
        <!-- 修改功能表单组件 -->
        <el-form ref="ruleFormRef" :model="dataForm" status-icon :rules="rules" class="demo-ruleForm" label-width="200px"
            :disabled="dialogTitle == '查看' ? true : false">
            <el-form-item prop="title" label="优惠券名称">
                <el-input class="fix_input" v-model.trim="dataForm.title" type="text" autocomplete="off"
                    placeholder="请输入优惠券名称" />
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type">
                <el-select class="frame" placeholder="请选择优惠券类型" v-model="dataForm.type">
                    <el-option v-for="item in couponType.slice(0, 2)" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item prop="description" label="介绍：">
                <el-input class="fix_input" v-model.trim="dataForm.description" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="total" label="优惠券数量：">
                <el-input v-model.trim="dataForm.total" class="fix_input">
                    <template #append>张</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="limit" label="每人限领：">
                <el-input v-model.trim="dataForm.limit" class="fix_input">
                    <template #append>张</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="discount" label="优惠金额：">
                <el-input v-model.trim="dataForm.discount" class="fix_input">
                    <template #append>元</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="min" label="最低消费：">
                <el-input v-model.trim="dataForm.min" class="fix_input">
                    <template #append>元</template>
                </el-input>
            </el-form-item>
            <el-form-item label="优惠券状态" prop="status">
                <el-select class="frame" placeholder="请选择优惠券状态" v-model="dataForm.status">
                    <el-option v-for="item in couponStatus.slice(0, 2)" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="有效期">
                <el-radio-group v-model="dataForm.timeType">
                    <el-radio-button :label="0">领劵相对天数
                    </el-radio-button>
                    <el-radio-button :label="1">指定绝对时间</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <el-form-item v-show="dataForm.timeType === 0" prom="dataForm.days" prop="days">

                <el-input v-model.trim="dataForm.days">
                    <template #append>天</template>
                </el-input>
            </el-form-item>
            <el-form-item v-show="dataForm.timeType === 1" prom="dataForm.days">
                <el-space>
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.gmtStart" type="datetime" placeholder="选择日期" value-format="x" />
                    </el-col>
                    <el-col :sapn="2">至</el-col>
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.gmtEnd" type="datetime" placeholder="选择日期" value-format="x" />
                    </el-col>
                </el-space>
            </el-form-item>

            <el-form-item label="商品限制范围">
                <el-radio-group v-model="dataForm.goodsType">
                    <el-radio-button :label="0">全场通用
                    </el-radio-button>
                    <el-radio-button :label="1">指定分类</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <el-form-item v-show="dataForm.goodsType === 1" label="优惠类目">
                <el-cascader :options="options" clearable :props="props" v-model="dataForm.categoryId" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sure(ruleFormRef);" v-if="dialogTitle !== '查看'">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { Search, Download, Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { post } from '@/utils/http';
import { nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination, ClassCoupon } from '#/index';
import { ElMessage } from "element-plus"
import { handleTime } from '@/utils/ProcessingTime'
import { ExcelService } from '@/execl/excel'
// 数据初始化
onMounted(() => {
    init()
})

// 控制对话框组件的显示隐藏
const dialogVisible = ref(false)
const options: Array<any> = reactive([])    //类目树结构
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let tableData: TypeCoupon[] = reactive([])               //表格数据
let listLoading = ref(false)            //加载效果
const dialogTitle = ref("")
// 对话框状态，采用枚举
// const dialogStats = ref(EnumDialogStats.create())

// 拓展对话框数据
class ClassDataForm extends ClassCoupon {
    /**
     * 有效期类型   0：相对天数     1：指定时间
     */
    timeType: number = 1 | 0;
    /**
     * 商品限制范围   0：全场通用     1：指定范围
     */
    goodsType: number = 1 | 0;
}


/**
 * 表单数据
 */
const dataForm = reactive(new ClassDataForm())
/**
 * 添加时清空参数
 */
let newForms = { ...dataForm }

/**
 * 表单验证
 */
const rules = {
    title: [
        { required: true, message: "优惠券名称不得为空！", trigger: 'blur' },
    ],
    type: [
        { required: true, message: "请选择优惠券类型！", trigger: 'blur' }
    ],
    description: [
        { required: true, message: "介绍内容不得为空！", trigger: 'blur' }
    ],
    total: [
        { required: true, message: "请输入优惠券数量", trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: "请输入正整数" }
    ],
    limit: [
        { required: true, message: "请输入每人限领的优惠券数量", trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: "请输入正整数" }
    ],
    discount: [
        { required: true, message: "请输入优惠金额", trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: "请输入正整数" }
    ],
    min: [
        { required: true, message: "请输入最低消费金额", trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: "请输入正整数" }
    ],
    status: [
        { required: true, message: "请选择优惠券状态！", trigger: 'blur' }
    ],
    days: [
        { pattern: /^[0-9]*$/, message: "请输入正整数" , trigger: 'blur'}
    ],
}

/**
 * 优惠券类型
 */
const couponType = reactive([
    { value: 1, label: "满减卷" },
    { value: 2, label: "立减卷" },
    { value: "", label: "全部" }
]);
/**
 * 优惠券状态
 */
const couponStatus = reactive([
    { value: 0, label: "下架" },
    { value: 1, label: "正常" },
    { value: -1, label: "已过期" },
    { value: "", label: "全部" }
]);
/**
 * 类目结构绑定的数据
 */
const props = {
    checkStrictly: true,
    children: "childrenList",
    value: "id",
    label: "title",
    emitPath: false
}

// 搜索所需的数据
let seacherData = reactive({
    title: "",
    type: undefined,
    status: undefined,
})
// 搜索操作
function search() {
    init()
}

getCategory()
/**
 * 请求类目数据
 */
function getCategory() {
    post({
        _gp: "admin.category",
        _mt: "categoryTree"
    }).then(res => {
        console.log(res.data)
        let { errmsg, errno } = res
        if (200 == errno) {
            options.length = 0
            options.push(...res.data)

        } else {
            ElMessage.error(errmsg)
        }

    })
}

// 添加操作
function addRole() {
    dialogTitle.value = "创建"
    Object.assign(dataForm, newForms)
    dialogVisible.value = true;
}
/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let couponListData = reactive({
        _gp: "admin.coupon",
        _mt: "list",
        title: seacherData.title,
        type: seacherData.type,
        status: seacherData.status,//用户状态
        pageNo: pagination.page,//当前页码
        limit: pagination.limit//每页页码长度
    })
    // 请求管理员列表接口拿到管理员列表信息
    post(couponListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data: { total, items }, errno, errmsg } = res
        if (200 === errno) {
            pagination.total = total
            items.forEach((item: TypeCoupon) => {
                const now = new Date()
                if (item.gmtEnd && item.gmtEnd < now.valueOf()) {
                    item.status = -1 //代表过期
                }
            })

            tableData.length = 0;

            tableData.push(...items)
            listLoading.value = false
            nextTick(() => {
                backTop.value.$el.click?.()
            })
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);

    })


}

const ruleFormRef = ref<FormInstance>()
//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleEdit = (index: number, row: TypeCoupon) => {
    dialogTitle.value = "查看"
    Object.assign(dataForm, row)
    dataForm.timeType = row.days ? 0 : 1
    dataForm.goodsType = row.categoryId ? 1 : 0
    dialogVisible.value = true;
    console.log(row)

}

/**
 * 冻结解冻操作
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleFreeze = (index: number, row: TypeCoupon) => {
    if (row.status == -1) {
        ElMessage.warning("无法修改已过期优惠券")
        return
    }

    let data = {
        _gp: 'admin.coupon',
        _mt: 'updateCouponStatus',
        id: row.id,
        status: row.status ? 0 : 1,
    }
    post(data).then(res => {
        console.log(res);

        let { data, errno } = res
        if (200 === errno) {
            ElMessage.success(row.status == 1 ? '冻结成功' : '激活成功')
            init()
        }
    }).catch(err => {
        console.log(err);
    })
}

/**
 * 添加功能
 * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {
    console.log(dataForm);

    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {

            if (dataForm.days == undefined && (dataForm.gmtStart == undefined || dataForm.gmtEnd == undefined)) {
                ElMessage.error("请填写优惠券使用区间！")
                return false
            }
            // 使用时间类型，不能为空，值要互斥
            if (dataForm.timeType === 1) {
                dataForm.days = undefined;
                if (!dataForm.gmtStart || !dataForm.gmtEnd || dataForm.gmtEnd < dataForm.gmtStart) {
                    ElMessage.error("请选择正确的日期")
                    return false
                }
            } else {
                dataForm.gmtStart = undefined;
                dataForm.gmtEnd = undefined;
                if (dataForm.days == undefined || dataForm.days === 0) {
                    ElMessage.error("请正确填写时长，不能为空或为0！")
                    return false
                }
            }
            // 判断全场通用，类型值为空
            if (dataForm.goodsType === 0) {
                dataForm.categoryId = undefined
            }

            // 对表单的满减金额和最低消费做处理
            dataForm.discount *= 100
            dataForm.min *= 100
            // 数据逻辑：最低消费金额大于优惠金额
            if (dataForm.discount > dataForm.min) {
                ElMessage.error("优惠金额不能高于最低消费！")
                return false
            }

            console.log("=====要提交的表单数据=====");
            console.log(dataForm);




            let data = {
                _gp: 'admin.coupon',
                _mt: 'create',
                ...dataForm
            }
            post(data).then(res => {
                console.log(res);

                let { errno } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    ElMessage.success('添加成功')
                    init()
                }
                resetForm(formEl)
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}

/**
 * 表单重置
 * @param formEl 表单验证结果
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}


// 导出
function handleDownload() {
    if (tableData.length > 0) {
        let dataList: Array<any> = [];
        dataList.push(["id", "优惠卷名称", "优惠卷类型", "介绍", "优惠卷数量", "剩余数量", "每人限领", "满减金额", "最低消费", "状态", "使用类目名称", "使用类目id", "领卷相对天数", "领卷开始时间", "领卷结束时间"]);
        tableData.forEach((item) => {
            dataList.push([item["id"], item["title"], item["type"] == 1 ? '立减' : '满减', item["description"], item["total"] + '张', item["surplus"], item["limit"], item["discount"], item["min"], item["status"] == 1 ? '正常' : '下架', item["categoryTitle"] ? '全部类目' : item["categoryTitle"], item["categoryId"], item["days"], item["gmtStart"] ? handleTime(item["gmtStart"], "ymdhmm") : "无", item["gmtEnd"] ? handleTime(item["gmtEnd"], "ymdhmm") : "无"]);
        });
        const s = new ExcelService();
        s.exportAsExcelFile(dataList, 'youhuiquan');
    }
}
</script>
  

<style scoped lang="less">
.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}
</style>